/**
 * チェックボックスコンポーネント
 * （実態はMaterial-UIのチェックボックス）
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Checkbox as MuCheckbox } from 'material-ui';

import iconChecked from './images/iconCheckboxOn.png';
import iconUnChecked from './images/iconCheckboxOff.png';

class Checkbox extends Component {
  constructor(props) {
    super(props);
    this.state = { checked: props.checked };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ checked: nextProps.checked });
  }

  handleChange(event, isInputChecked) {
    const { name } = this.props;
    this.setState({ checked: isInputChecked }, () => {
      if (this.props.propagate(name, isInputChecked) !== false) {
        this.props.onChange(name, isInputChecked);
      }
    });
  }

  render() {
    const { name, checked, className, disabled, onChange, propagate, ...other } = this.props;    // eslint-disable-line no-unused-vars
    return (
      <div className="CheckboxContainer" style={{ display: 'inline-block' }}>
        <MuCheckbox
          {...other}
          id={name}
          name={name}
          className={classNames('Checkbox', className, {
            'disabled': disabled,
          })}
          labelStyle={{
            whiteSpace: 'nowrap',
            paddingLeft: '13px',
          }}
          checked={this.state.checked}
          disabled={disabled}
          checkedIcon={<img src={iconChecked} alt="" width={24} height={24} />}
          uncheckedIcon={<img src={iconUnChecked} alt="" width={24} height={24} />}
          onCheck={this.handleChange.bind(this)}
        />
      </div>
    );
  }
}

Checkbox.propTypes = {
  name: PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
    id: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    choices: PropTypes.array.isRequired,
  })]).isRequired,                      // id
  checked: PropTypes.bool,              // 選択状態（初期値）
  className: PropTypes.string,          // class属性
  style: PropTypes.object,              // style属性
  disabled: PropTypes.bool,             // disabled属性
  onChange: PropTypes.func,             // change event handler
  propagate: PropTypes.func.isRequired, // 親stateを更新するcallback
}

Checkbox.defaultProps = {
  checked: false,       // 初期値なし
  disabled: false,
  onChange: () => {},
  propagate: () => {},
}

export default Checkbox
